import { CopyOutlined } from '@ant-design/icons';
import { Flex, Table, Tag, Tooltip, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useCallback, useEffect, useState } from 'react';
import { useSearchParams } from 'umi';
import styles from './index.less';

import videoGet, { getVideoDetail } from '@/services/video-service';
import VideoPlayer from './SimplePlayer';

interface VideoItem {
  id: string;
  key: string;
  name: string;
  duration: number; // MM:SS
  uploadTime: string; // YYYY-MM-DD
  videoUrl: string;
  coverUrl: string;
  FileId: string;
}

// 转换函数
const convertVideoItem = (data: any): VideoItem[] => {
  const videoList = data.MediaInfoSet;
  return videoList.map((item: any) => ({
    id: item.BasicInfo.Vid,
    key: item.BasicInfo.Vid,
    name: item.BasicInfo.Name,
    duration: item.MetaData.Duration,
    uploadTime: item.BasicInfo.CreateTime,
    videoUrl: item.BasicInfo.MediaUrl,
    coverUrl: item.BasicInfo.CoverUrl,
    FileId: item.FileId,
  }));
};

const VideoManagement = () => {
  const [currentVideo, setCurrentVideo] = useState<string>('');
  const [videoItem, setVideoItem] = useState<VideoItem[]>([]);

  function VideoSrcGet() {
    const [searchParams] = useSearchParams();
    const videoId = searchParams.get('id');
    useEffect(() => {
      if (videoId) {
        // 请求接口或处理数据
        try {
          getVideoDetail(videoId).then((res) => {
            setCurrentVideo(res.data.data.VideoUrl);
          });
        } catch (error) {
          console.log(error);
        }
      }
    }, [videoId]);
  }
  VideoSrcGet();

  const videoListGet = async () => {
    try {
      const res = await videoGet.get_videos();
      setVideoItem(convertVideoItem(res.data.data));
    } catch (error) {
      console.error('获取视频列表失败:', error);
    }
  };

  useEffect(() => {
    videoListGet();
  }, []);
  // 格式化时间为 MM:SS
  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // 格式化日期为 YYYY-MM-DD
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toISOString().split('T')[0].replace(/-/g, '-');
  };

  const handleCopyFileId = (text: string) => {
    navigator.clipboard.writeText(text);
    // You can add a notification here if needed
    message.success('FileId已复制到剪贴板');
  };

  const columns: ColumnsType<VideoItem> = [
    {
      title: '',
      dataIndex: 'info',
      render: (_, record) => (
        <div className={styles.videoRow}>
          {/* 左侧图片部分 */}
          <div className={styles.thumbnailContainer}>
            <img
              src={record.coverUrl}
              alt="封面"
              className={styles.thumbnail}
            />
            <div className={styles.durationBadge}>
              {formatDuration(record.duration)}
            </div>
          </div>

          {/* 右侧详细信息部分 */}
          <div className={styles.detailsContainer}>
            <div className={styles.videoName}>{record.name}</div>
            <div className={styles.uploadTime}>
              {formatDate(record.uploadTime)}
            </div>
            <div
              className={styles.fileIdContainer}
              onClick={(e) => e.stopPropagation()}
            >
              <Tooltip title="点击复制">
                <Tag
                  icon={<CopyOutlined />}
                  color="blue"
                  onClick={() => handleCopyFileId(record.FileId)}
                  className={styles.fileIdTag}
                >
                  {record.FileId}
                </Tag>
              </Tooltip>
            </div>
          </div>
        </div>
      ),
    },
  ];

  const handleVideoSelect = useCallback((record: VideoItem) => {
    setCurrentVideo(record.videoUrl);
  }, []);

  const [isExpanded, setIsExpanded] = useState(false);

  const handleIsExpandedChange = useCallback(() => {
    setIsExpanded(!isExpanded);
  }, [isExpanded]);
  return (
    <Flex className={styles.container}>
      <VideoPlayer
        isExpanded={isExpanded}
        onIsExpandedChange={handleIsExpandedChange}
        className={styles.videoPlayer}
        src={currentVideo}
      />

      <div
        className={styles.listContainer}
        style={{
          transform: isExpanded
            ? 'translateX(calc(100% - 10px))'
            : 'translateX(0)',
        }}
      >
        <Table
          columns={columns}
          dataSource={videoItem}
          showHeader={false} // 隐藏表头
          onRow={(record) => ({
            onClick: () => handleVideoSelect(record),
          })}
          pagination={false}
          rowKey="key"
          className={styles.videoTable}
        />
      </div>
    </Flex>
  );
};

export default VideoManagement;
